package com.iot.iotplus.utils;

import java.time.Instant;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;

public class SnowflakeIdGenerator {
    private static final long EPOCH = Instant.parse("2022-01-01T00:00:00.00Z").toEpochMilli(); // 设置起始时间，这里以2022-01-01为例
    private static final long DATA_CENTER_ID_BITS = 5L; // 数据中心ID所占位数
    private static final long WORKER_ID_BITS = 5L; // 机器ID所占位数
    private static final long SEQUENCE_BITS = 12L; // 序列号所占位数
    private static final long MAX_DATA_CENTER_ID = ~(-1L << DATA_CENTER_ID_BITS); // 支持的最大数据中心ID
    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS); // 支持的最大机器ID
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS); // 序列号掩码
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS; // 机器ID左移位数
    private static final long DATA_CENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS; // 数据中心ID左移位数
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATA_CENTER_ID_BITS; // 时间戳左移位数
    private static final long SEQUENCE_RESET_THRESHOLD = ~(-1L << (SEQUENCE_BITS - 1)); // 序列号溢出阈值

    private final long dataCenterId; // 数据中心ID
    private final long workerId; // 工作机器ID
    private final AtomicLong sequence = new AtomicLong(0L); // 序列号
    private volatile long lastTimestamp = -1L; // 上次生成ID的时间戳

    public SnowflakeIdGenerator(long dataCenterId, long workerId) {
        if (dataCenterId > MAX_DATA_CENTER_ID || dataCenterId < 0) {
            throw new IllegalArgumentException("Data center ID can't be greater than " + MAX_DATA_CENTER_ID + " or less than 0");
        }
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID can't be greater than " + MAX_WORKER_ID + " or less than 0");
        }
        this.dataCenterId = dataCenterId;
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = currentTimeMillis();
        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id for " + (lastTimestamp - timestamp) + " milliseconds");
        }
        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            // 序列号自增，与SEQUENCE_RESET_THRESHOLD取模以避免溢出
            sequence.set((sequence.get() + 1) & SEQUENCE_RESET_THRESHOLD);
            // 如果序列号超过阈值，阻塞到下一个毫秒，重新生成
            if (sequence.get() == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 时间戳改变，序列号重置
            sequence.set(0L);
        }
        // 上次生成ID的时间戳更新为当前时间戳
        lastTimestamp = timestamp;
        // 生成ID
        return ((timestamp - EPOCH) << TIMESTAMP_LEFT_SHIFT) | (dataCenterId << DATA_CENTER_ID_SHIFT) | (workerId << WORKER_ID_SHIFT) | sequence.get();
    }

    private long currentTimeMillis() {
        return System.currentTimeMillis();
    }

    private long tilNextMillis(long lastTimestamp) {
        long timestamp = currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = currentTimeMillis();
        }
        return timestamp;
    }
    public static Long getSnowflakeId(){
        SnowflakeIdGenerator idGen = new SnowflakeIdGenerator(0, 0); // 这里的数据中心ID和机器ID需要根据实际情况设置
        Random random = new Random();
        int i = random.nextInt(10);
        long id = idGen.nextId()*10+i;
        return id;
    }

    public static String generateSixDigitRandomNumber() {
        Random random = new Random();
        // 生成0到999999之间的随机数
        int randomNumber = random.nextInt(900000) + 100000;
        // 确保字符串为六位数，前面补0
        String formattedNumber = String.format("%6d", randomNumber);
        return formattedNumber;
    }

    public static void main(String[] args) {
        Long id = getSnowflakeId();
        System.out.println(id);
    }

}
